package megamu.mesh;

import java.util.ArrayList;
import java.util.Collections;

import com.jellyfishumbrella.Site;
import com.jellyfishumbrella.Vertex;
import com.jellyfishumbrella.GL.Normal;

public class Region {
	public Site					site;
	private ArrayList<Vertex>	verts = new ArrayList<Vertex>();
	int							count;

	public Region() {
		this(0);
	}

	public Region(int points) {
		verts = new ArrayList<Vertex>();
		count = 0;
	}

	public void add(float x, float y) {
		verts.add(new Vertex(x, 0, y));
	}

	public void add(Vertex vertex) {
		verts.add(vertex);
	}

	public int vertCount() {
		return verts.size();
	}

	public ArrayList<Vertex> getVerts() {
		return verts;
	}

	public String toString() {
		String str = "MPolygon: ";
		for (int i = 0; i < verts.size(); i++) {
			str += verts.get(i).toString();
		}
		return str;
	}


	public void pointNormalsUp() {
		Normal normal = computeTriangleNormal(verts.get(1), verts.get(2));
		double dotProduct = normal.x * 0 + normal.y * 1 + normal.z * 0;
		if (dotProduct > 0) {
			Collections.reverse(verts);
			//pointNormalsUp();
		}
	}

	public Normal computeTriangleNormal(Vertex corner1, Vertex corner2) {
		Normal a = new Normal();// normals
		Normal b = new Normal();// normals

		Normal normal = new Normal();
		normal.x = 0.0f;
		normal.y = 0.0f;
		normal.z = 0.0f;

		a.x = corner1.x - site.x;
		a.y = corner1.y - site.y;
		a.z = corner1.z - site.z;

		b.x = corner2.x - site.x;
		b.y = corner2.y - site.y;
		b.z = corner2.z - site.z;

		normal.x = (float) (b.y * a.z - b.z * a.y);
		normal.y = (float) (b.z * a.x - b.x * a.z);
		normal.z = (float) (b.x * a.y - b.y * a.x);

		normal.normalize();
		return normal;
	}

	public void computeNormal() {

		Normal avgNormal = new Normal();
		avgNormal.x = 0.0f;
		avgNormal.y = 0.0f;
		avgNormal.z = 0.0f;

		for (int i = 1; i < verts.size()-1; i++) {
			Normal normal = computeTriangleNormal(verts.get(i), verts.get(i+1));

			avgNormal.x += normal.x;
			avgNormal.y += normal.y;
			avgNormal.z += normal.z;
		}

		avgNormal.x /= verts.size();
		avgNormal.y /= verts.size();
		avgNormal.z /= verts.size();

		avgNormal.normalize();

		verts.get(0).normal = site.normal = avgNormal;
	}
}